package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.common.vo.MemberRespVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 社交登录
 */
@Controller
public class Oauth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session){
        //根据code换取access_token
        String url="https://api.weibo.com/oauth2/access_token";
        Map<String,Object> paramMap=new HashMap<>();
        paramMap.put("client_id","3202024361");
        paramMap.put("client_secret","6b8a0a2a59ec8ac357851a07d30958a1");
        paramMap.put("grant_type","authorization_code");
        paramMap.put("code",code);
        paramMap.put("redirect_uri","http://auth.gulimall.com/oauth/weibo/success");
        String access_map = HttpUtils.doPost(url, paramMap);

//        Map<String,String> accessMap = JSON.parseObject(access_map, Map.class);

        R r = memberFeignService.oauthLogin(access_map);
        if (r.getCode()==0){
            MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {
            });

            session.setAttribute("loginUser",data);
            return "redirect:http://gulimall.com";
        }

        return "redirect:http://auth.gulimall.com/login.html";
    }
}
